package com.zhou.framework.util;

import com.zhou.util.KeyValue;
import com.zhou.util.enums.AbstractEnum;
import com.zhou.framework.aop.enums.LogLevelEnum;
import org.apache.commons.collections.MapUtils;

import java.util.*;

/**
 * @author lang.zhou
 * @since 2023/3/6 15:30
 */
public class EnumClassUtil {
    /*
     * 枚举属性缓存
     */
    private static Map<String, List<AbstractEnum<?>>> cacheMap = new HashMap<>(5);

    @SuppressWarnings("unchecked")
    public static <T extends AbstractEnum<E>,E> List<T> list(Class<T> t){
        EnumClassReader<T,E> reader = new EnumClassReader<>(t);
        String name = reader.getClazz().getName();
        List<AbstractEnum<?>> list = cacheMap.computeIfAbsent(name,l -> (List<AbstractEnum<?>>) reader.list());
        return (List<T>) list;
    }


    public static <T extends AbstractEnum<E>,E> Map<E,String> map(Class<T> c){
        List<T> list = list(c);
        Map<E,String> r = new LinkedHashMap<>(list.size());
        for (AbstractEnum<E> e : list) {
            r.put(e.getEnumValue(), e.getEnumName());
        }
        return r;
    }

    public static <T extends AbstractEnum<E>,E> String getName(Class<T> c, E key, String dv){
        Map<E,String> r = map(c);
        return MapUtils.getString(r,key,dv);
    }

    public static <T extends AbstractEnum<E>,E> String getName(Class<T> c, E key){
        Map<E,String> r = map(c);
        return MapUtils.getString(r,key,"");
    }

    public static <T extends AbstractEnum<E>,E> T get(Class<T> c, E k){
        List<T> list = list(c);
        for (T item : list) {
            if(Objects.equals(item.getEnumValue(),k)){
                return item;
            }
        }
        return null;
    }
    public static <T extends AbstractEnum<E>,E> T get(Class<T> c, E k,T t){
        T r = get(c,k);
        if(r == null){
            return t;
        }
        return r;
    }

    public static <T extends AbstractEnum<E>,E> List<E> keyList(Class<T> c){
        List<T> list = list(c);
        List<E> r = new ArrayList<>(list.size());
        for (T e : list) {
            r.add(e.getEnumValue());
        }
        return r;
    }

    public static <T extends AbstractEnum<E>,E> List<KeyValue> keyValueList(Class<T> c){
        List<T> list = list(c);
        List<KeyValue> r = new ArrayList<>(list.size());
        for (T e : list) {
            r.add(new KeyValue(e.getEnumValue(),e.getEnumName()));
        }
        return r;
    }

    public static void main(String[] args) {

        System.out.println(list(LogLevelEnum.class));
    }
}
